package com.ddd.config;

import com.ddd.core.constants.EncryptorConstants;
import com.ulisesbocchio.jasyptspringboot.EncryptablePropertyDetector;
import com.ulisesbocchio.jasyptspringboot.detector.DefaultPropertyDetector;
import com.ulisesbocchio.jasyptspringboot.encryptor.DefaultLazyEncryptor;
import org.jasypt.encryption.StringEncryptor;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

/**
 * @description:
 * @author: zhongwenbin
 * @date: 2024-10-22 11:33
 **/
@Configuration
public class EncryptorAutoConfiguration {

    public static boolean propertyExists(Environment environment, String key) {
        return environment.getProperty(key) != null;
    }

    public static String getProperty(Environment environment, String key, String defaultValue) {
        return environment.getProperty(key, defaultValue);
    }

    /**
     * @see DefaultLazyEncryptor
     * createDefault(Environment)
     */
    @Bean(EncryptorConstants.STRING_ENCRYPTOR_BEAN_NAME)
    public StringEncryptor jasyptStringEncryptor(Environment e) {
        PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        config.setPassword(getProperty(e, "jasypt.encryptor.password", EncryptorConstants.DEFAULT_JASYPT_ENCRYPTOR_PASSWORD));
        config.setAlgorithm(getProperty(e, "jasypt.encryptor.algorithm", EncryptorConstants.DEFAULT_JASYPT_ENCRYPTOR_ALGORITHM));
        config.setKeyObtentionIterations(getProperty(e, "jasypt.encryptor.keyObtentionIterations", "1000"));
        config.setPoolSize(getProperty(e, "jasypt.encryptor.poolSize", "1"));
        config.setProviderName(getProperty(e, "jasypt.encryptor.providerName", "SunJCE"));
        config.setProviderClassName(getProperty(e, "jasypt.encryptor.providerClassName", "com.sun.crypto.provider.SunJCE"));
        config.setIvGeneratorClassName(getProperty(e, "jasypt.encryptor.ivGeneratorClassname", "org.jasypt.iv.RandomIvGenerator"));
        config.setSaltGeneratorClassName(getProperty(e, "jasypt.encryptor.saltGeneratorClassname", "org.jasypt.salt.RandomSaltGenerator"));
        config.setStringOutputType(getProperty(e, "jasypt.encryptor.stringOutputType", "base64"));
        encryptor.setConfig(config);
        return encryptor;
    }

    @Bean(EncryptorConstants.ENCRYPTABLE_PROPERTY_DETECTOR_BEAN_NAME)
    public EncryptablePropertyDetector encryptablePropertyDetector(Environment e) {
        return new DefaultPropertyDetector(
                getProperty(e, "jasypt.encryptor.property.prefix",
                        EncryptorConstants.DEFAULT_JASYPT_PREFIX),
                getProperty(e, "jasypt.encryptor.property.suffix",
                        EncryptorConstants.DEFAULT_JASYPT_SUFFIX));
    }


}
